import json

import redis
from sqlalchemy.orm import load_only
from models.user import UserModel


class UserCache:

    """
    用户信息缓存相关
    """
    def __init__(self, user_id):
        self.key = 'user:{}:profile'.format(user_id)
        self.user_id = user_id

    def get(self):

        """
        从Redis中获取用户缓存信息
        """
        # 思路:
        # 查询Redis中的缓存记录
        # 如果记录存在, 则直接返回
        # 如果记录不存在
        #     去数据库中查询, 如果数据库中存在, 则设置Redis缓存记录, 并返回查询数据
        #     数据库中如果没有记录, 设置Redis中记录的值为-1
        # 返回值
        print("user_id", self.user_id)
        key = 'user:{}:profile'.format(self.user_id)
        print("key", key)
        rds = redis.Redis()
        ret = rds.get(key)
        if ret is not None:
            if ret == b'1':
                return None
            else:
                user_dict = json.loads(ret)
                print("user_dict>>>>>1", user_dict)
                return user_dict
        else:
            user = UserModel.query.options(load_only(
                UserModel.mobile,
                UserModel.uname,
                UserModel.gender,
                UserModel.created_time,
                UserModel.profile_photo,
                UserModel.is_media,
                UserModel.introduction,
                UserModel.certificate,
                UserModel.article_count,
                UserModel.following_count,
                UserModel.fans_count,
                UserModel.like_count,
            )).filter_by(uid=self.user_id).first()
            print("user", user)
            if user is None:
                rds.setex(key, 5 * 60, -1)
                return None
            else:

                user_dict = {
                    'mobile': user.mobile,
                    'uname': user.uname,
                    'gender': user.gender,
                    'profile_photo': user.profile_photo,
                    'created_time': str(user.created_time),
                    'is_media': user.is_media,
                    'introduction': user.introduction,
                    'certificate': user.certificate,
                    'article_count': user.article_count,
                    'following_count': user.following_count,
                    'fans_count': user.fans_count,
                    'like_count': user.like_count,
                }
                print("user_dict>>>>2", user_dict)
                print("user_dict>>>>2", json.loads(json.dumps(user_dict)))
                rds.setex(key, 1 * 60 * 60, json.dumps(user_dict))
            return user_dict

